package edu.ntu.im.p2ptrade.metadata;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import edu.ntu.im.p2ptrade.DialogHost;
import edu.ntu.im.p2ptrade.P2PTrade;
import edu.ntu.im.p2ptrade.Util;
import edu.ntu.im.p2ptrade.entity.Item;
import edu.ntu.im.p2ptrade.msg.SearchItemQuery;
import net.jxta.share.ContentAdvertisement;
import net.jxta.share.client.ListContentRequest;

public class MetaDataSearcher {
	private static final Object WILDCARD = "*";

	private static HashMap<String, LinkedList<Item>> itemmap = new HashMap<String, LinkedList<Item>>();

	private ListContentRequest requestor = null;

	private String term;

	public void search(String term) {
		this.term = term;
		String criteria = (term.trim().length() == 0
				|| term.trim().equals(WILDCARD) ? null : term);
		//this.TestProcess();
		SearchItemQuery siq = new SearchItemQuery(criteria);
		Util.transdferMessageToPeer(siq.getMessageToTransfer(), DialogHost.ALL);
	}

/*	private void TestProcess() {
		Item item = new Item();
		item.setName("bible");
		item.setId(1);
		item.setOwnerId("adam0502");
		item.setMemo("haha");
		item.setPhotoUrl("test.com");

		LinkedList<Item> ItemList = new LinkedList<Item>();
		if (itemmap.get(this.term) != null)
			ItemList = itemmap.get(this.term);
		ItemList.add(item);
		itemmap.put(this.term, ItemList);
	}*/

	private void process(ContentAdvertisement[] ca) {
		for (int i = 0; ca != null && i < ca.length; i++) {
			// System.out.println("search result:"+ca[i].getName());
			// System.out.println("search result:"+ca[i].getDescription());
			String ItemName = ca[i].getName();

			String[] ItemArray = {};
			ItemArray = ca[i].getDescription().split("**");
			String ItemId = ItemArray[0];
			String ItemOwnerId = ItemArray[1];
			String ItemMemo = ItemArray[2];
			String ItemPhotoURL = ItemArray[3];

			Item item = new Item(ItemOwnerId, ItemName);
//			item.setName(ItemName);
			item.setId(Integer.parseInt(ItemId));
//			item.setOwnerId(ItemOwnerId);
			item.setMemo(ItemMemo);
			item.setPhotoUrl(ItemPhotoURL);

			LinkedList<Item> ItemList = new LinkedList<Item>();
			if (itemmap.get(this.term) != null)
				ItemList = itemmap.get(this.term);
			ItemList.add(item);
			itemmap.put(this.term, ItemList);
		}
	}

	public static HashMap<String, LinkedList<Item>> getItemMap() {
		return itemmap;
	}

	public static void recieveResult(String query, List<Item> items) {
		if (itemmap.get(query)==null){
			itemmap.put(query, new LinkedList<Item>());
		}
		itemmap.get(query).addAll(items);
	}
}
